#include "hzpch.h"
#include "WindowsWindow.h"

#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#include "./Hazel/Core/Log.h"

// ImGui头文件
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"

// OpenGL加载器
#include <glad/glad.h>

namespace Hazel
{

    static uint8_t s_GLFWWindowCount = 0;
    static void GLFWErrorCallback(int error, const char *description)
    {
        HZ_CORE_ERROR("GLFW Error ({0}): {1}", error, description);
    }

    WindowsWindow::WindowsWindow(const WindowProps &props)
    {
        Init(props);
    }

    WindowsWindow::~WindowsWindow()
    {
        Shutdown();
    }

    void WindowsWindow::Init(const WindowProps &props)
    {
        m_Data.Title = props.Title;
        m_Data.Width = props.Width;
        m_Data.Height = props.Height;

        HZ_CORE_INFO("Creating window {0} ({1}, {2})", props.Title, props.Width, props.Height);

        if (s_GLFWWindowCount == 0)
        {
            int success = glfwInit();
            HZ_CORE_ASSERT(success, "Could not initialize GLFW!");
            glfwSetErrorCallback(GLFWErrorCallback);
        }

        m_Window = glfwCreateWindow((int)props.Width, (int)props.Height, m_Data.Title.c_str(), nullptr, nullptr);
        if (!m_Window) {
            HZ_CORE_ERROR("Failed to create GLFW window");
            return;
        }
        
        glfwMakeContextCurrent(m_Window);
        if (glfwGetCurrentContext() == nullptr) {
            HZ_CORE_ERROR("Failed to make GLFW context current");
            return;
        }
        
        // ===== 初始化GLAD =====
        if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
        {
            HZ_CORE_ERROR("Failed to initialize GLAD");
            return;
        }
        HZ_CORE_INFO("OpenGL version: {0}", reinterpret_cast<const char*>(glGetString(GL_VERSION)));
        // =====================
        
        s_GLFWWindowCount++;

        glfwSetWindowUserPointer(m_Window, &m_Data);
        SetVSync(true);
    }

    void WindowsWindow::Shutdown()
    {
        // 先关闭ImGui
        ShutdownImGui();
        
        // 然后关闭GLFW窗口
        glfwDestroyWindow(m_Window);
        s_GLFWWindowCount--;

        if (s_GLFWWindowCount == 0)
        {
            glfwTerminate();
        }
    }

    void WindowsWindow::OnUpdate()
    {
        glfwPollEvents();
        glfwSwapBuffers(m_Window);
    }

    void WindowsWindow::SetVSync(bool enabled)
    {
        if (enabled)
            glfwSwapInterval(1);
        else
            glfwSwapInterval(0);

        m_Data.VSync = enabled;
    }

    bool WindowsWindow::IsVSync() const
    {
        return m_Data.VSync;
    }

    // ===== ImGui初始化函数 =====
    void WindowsWindow::InitImGui()
    {
        if (m_ImGuiInitialized) {
            HZ_CORE_WARN("ImGui is already initialized");
            return;
        }

        if (!m_Window) {
            HZ_CORE_ERROR("Cannot initialize ImGui: GLFW window is null");
            return;
        }
        
        // 确保当前上下文
        glfwMakeContextCurrent(m_Window);
        
        // ImGui初始化
        IMGUI_CHECKVERSION();
        ImGui::CreateContext();
        ImGuiIO& io = ImGui::GetIO();
        io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // 启用键盘控制
        
        // 设置样式
        ImGui::StyleColorsDark();
        
        // 初始化平台后端
        if (!ImGui_ImplGlfw_InitForOpenGL(m_Window, true)) {
            HZ_CORE_ERROR("Failed to initialize ImGui GLFW backend");
            return;
        }
        
        // 初始化渲染器后端 - 这是解决断言错误的关键！
        const char* glsl_version = "#version 330";
        if (!ImGui_ImplOpenGL3_Init(glsl_version)) {
            HZ_CORE_ERROR("Failed to initialize ImGui OpenGL3 backend");
            ImGui_ImplGlfw_Shutdown();
            ImGui::DestroyContext();
            return;
        }
        
        m_ImGuiInitialized = true;
        HZ_CORE_INFO("ImGui initialized successfully");
    }

    void WindowsWindow::BeginImGuiFrame()
    {
        if (!m_ImGuiInitialized) {
            HZ_CORE_ERROR("ImGui not initialized. Call InitImGui() first");
            return;
        }
        
        // 开始新的ImGui帧
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();
    }

    void WindowsWindow::EndImGuiFrame()
    {
        if (!m_ImGuiInitialized) return;
        
        // 渲染ImGui
        ImGui::Render();
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
    }

    void WindowsWindow::ShutdownImGui()
    {
        if (!m_ImGuiInitialized) return;
        
        ImGui_ImplOpenGL3_Shutdown();
        ImGui_ImplGlfw_Shutdown();
        ImGui::DestroyContext();
        
        m_ImGuiInitialized = false;
        HZ_CORE_INFO("ImGui shutdown completed");
    }

}